package weaver.workflow.cms.xiao.utils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * @author XiaoBokang
 * @create 2021/8/13 17:43
 */

public class SqlUtil {

    /**
     * 构建插入的sql语句
     * @param tableName
     * @param param
     * @param params
     * @return
     */
    public static String buildInsert(String tableName, Map<String ,Object> param,List<Object> params){

        StringBuilder keyBuilder = new StringBuilder();
        StringBuilder valueBuilder = new StringBuilder();

        keyBuilder.append("insert into ")
                .append(tableName)
                .append(" (");
        valueBuilder.append(" values (");
        param.forEach((key,value) ->{
            keyBuilder.append(key);
            keyBuilder.append(",");
            valueBuilder.append("?");
            valueBuilder.append(",");
            params.add(value);
        });
        String keySql = keyBuilder.substring(0,keyBuilder.length()-1);
        String valueSql = valueBuilder.substring(0,valueBuilder.length()-1);

        return keySql+") "+valueSql+")";
    }

    public static String buildUpdate(String tableName, Map<String ,Object> param,List<Object> params){

        StringBuilder updateBuilder = new StringBuilder();

        updateBuilder.append("update ")
                .append(tableName)
                .append(" set ");
        param.forEach((k,v)->{
            updateBuilder.append(k).append(" = ?,");
            params.add(v);

        });
        String updateSql = updateBuilder.substring(0,updateBuilder.length()-1)+" ";

        return updateSql;
    }

    public static String buildUpdate(String tableName, Object obj,List<Object> params){

        StringBuilder updateBuilder = new StringBuilder();

        updateBuilder.append("update ")
                .append(tableName)
                .append(" set ");
        Field[] fields = obj.getClass().getFields();
        try{
            for (Field field : fields) {
                field.setAccessible(true);
                updateBuilder.append(field.getName()).append(" = ?,");
                params.add(field.get(obj));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        String updateSql = updateBuilder.substring(0,updateBuilder.length()-1)+" ";

        return updateSql;
    }

}
